<template>
  <div class="history-browser">
    <el-container>
      <!-- Header -->
      <el-header class="browser-header">
        <div class="header-left">
          <h2>历史版本浏览器</h2>
          <el-tag v-if="currentVersionData" type="info" size="small">
            {{ formatVersionId(currentVersionData.id) }}
          </el-tag>
        </div>
        <div class="header-right">
          <el-button-group>
            <el-button 
              :icon="Refresh" 
              @click="refreshVersions"
              :loading="isLoading"
              size="small"
            >
              刷新
            </el-button>
            <el-button 
              :icon="Setting" 
              @click="showSettings = true"
              size="small"
            >
              设置
            </el-button>
            <el-button 
              :icon="ArrowLeft" 
              @click="$router.push('/')"
              size="small"
            >
              返回首页
            </el-button>
          </el-button-group>
        </div>
      </el-header>

      <el-container class="main-container">
        <!-- Sidebar - Version List -->
        <el-aside 
          :width="sidebarCollapsed ? '60px' : `${panelSizes.sidebar}px`"
          class="version-sidebar"
        >
          <div class="sidebar-header">
            <el-button 
              :icon="sidebarCollapsed ? Expand : Fold"
              @click="toggleSidebar"
              text
              size="small"
            />
            <span v-if="!sidebarCollapsed" class="sidebar-title">版本列表</span>
          </div>
          
          <div v-if="!sidebarCollapsed" class="version-list">
            <el-scrollbar height="100%">
              <div v-if="isLoading && versions.length === 0" class="loading-placeholder">
                <el-skeleton :rows="5" animated />
              </div>
              
              <div v-else-if="!hasVersions" class="empty-placeholder">
                <el-empty description="未找到历史版本" />
                <el-button @click="refreshVersions" type="primary" size="small">
                  重新扫描
                </el-button>
              </div>
              
              <div v-else class="version-items">
                <div
                  v-for="version in versions"
                  :key="version.id"
                  :class="[
                    'version-item',
                    { 'active': currentVersion === version.id }
                  ]"
                  @click="selectVersion(version.id)"
                >
                  <div class="version-info">
                    <div class="version-id">{{ formatVersionId(version.id) }}</div>
                    <div class="version-meta">
                      <el-text size="small" type="info">
                        {{ formatDate(version.timestamp) }}
                      </el-text>
                      <el-text size="small" type="info">
                        {{ version.fileCount }} 文件
                      </el-text>
                    </div>
                  </div>
                  <el-icon v-if="version.hasEntriesFile" class="entries-icon">
                    <Document />
                  </el-icon>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </el-aside>

        <!-- Main Content Area -->
        <el-container class="content-container">
          <!-- File Tree -->
          <el-main class="file-tree-container">
            <div class="tree-header">
              <div class="tree-title">
                <el-icon><FolderOpened /></el-icon>
                <span>文件结构</span>
                <el-tag v-if="selectedFiles.length > 0" size="small" type="primary">
                  已选择 {{ selectedFiles.length }} 个文件
                </el-tag>
              </div>
              
              <div class="tree-actions">
                <el-button-group size="small">
                  <el-button @click="expandAllFolders" :icon="Plus">展开全部</el-button>
                  <el-button @click="collapseAllFolders" :icon="Minus">折叠全部</el-button>
                  <el-button 
                    @click="selectAllFiles" 
                    :disabled="currentVersionFiles.length === 0"
                    :icon="Select"
                  >
                    全选
                  </el-button>
                  <el-button 
                    @click="clearSelection" 
                    :disabled="selectedFiles.length === 0"
                    :icon="Close"
                  >
                    清除选择
                  </el-button>
                </el-button-group>
              </div>
            </div>

            <div class="tree-content">
              <el-scrollbar height="100%">
                <div v-if="isLoading && currentVersionFiles.length === 0" class="loading-placeholder">
                  <el-skeleton :rows="8" animated />
                </div>
                
                <div v-else-if="!currentVersion" class="empty-placeholder">
                  <el-empty description="请选择一个版本查看文件" />
                </div>
                
                <div v-else-if="currentVersionFiles.length === 0" class="empty-placeholder">
                  <el-empty description="该版本中没有文件" />
                </div>
                
                <FileTreeNode
                  v-else
                  v-for="node in currentVersionFiles"
                  :key="node.id"
                  :node="node"
                  :selected-files="selectedFiles"
                  :expanded-folders="expandedFolders"
                  @toggle-selection="toggleFileSelection"
                  @toggle-folder="toggleFolder"
                  @show-file-info="showFileInfo"
                  @show-file-history="showFileHistory"
                  @preview-file="previewFile"
                />
              </el-scrollbar>
            </div>
          </el-main>

          <!-- Details Panel -->
          <el-aside 
            :width="`${panelSizes.details}px`"
            class="details-panel"
            v-if="showDetailsPanel"
          >
            <div class="details-header">
              <el-tabs v-model="activeDetailsTab" type="card">
                <el-tab-pane label="文件信息" name="info">
                  <FileInfoPanel 
                    v-if="selectedFileInfo"
                    :file-info="selectedFileInfo"
                    :version-id="currentVersion"
                  />
                  <el-empty v-else description="选择文件查看详细信息" />
                </el-tab-pane>
                
                <el-tab-pane label="历史记录" name="history">
                  <FileHistoryPanel
                    v-if="selectedFileHistory"
                    :history="selectedFileHistory"
                    :current-version="currentVersion"
                    @select-version="selectVersion"
                  />
                  <el-empty v-else description="选择文件查看历史记录" />
                </el-tab-pane>
                
                <el-tab-pane label="内容预览" name="preview">
                  <FilePreviewPanel
                    v-if="selectedFilePreview"
                    :content="selectedFilePreview.content"
                    :file-path="selectedFilePreview.path"
                    :version-id="currentVersion"
                  />
                  <el-empty v-else description="选择文件预览内容" />
                </el-tab-pane>
              </el-tabs>
              
              <el-button 
                @click="showDetailsPanel = false"
                :icon="Close"
                text
                size="small"
                class="close-details"
              />
            </div>
          </el-aside>
        </el-container>
      </el-container>
    </el-container>

    <!-- Settings Dialog -->
    <el-dialog v-model="showSettings" title="浏览器设置" width="500px">
      <el-form label-width="120px">
        <el-form-item label="自动刷新">
          <el-switch v-model="autoRefresh" />
        </el-form-item>
        <el-form-item label="显示隐藏文件">
          <el-switch v-model="showHiddenFiles" />
        </el-form-item>
        <el-form-item label="文件大小显示">
          <el-radio-group v-model="fileSizeFormat">
            <el-radio label="bytes">字节</el-radio>
            <el-radio label="human">人类可读</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettings = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { 
  ArrowLeft, 
  Refresh, 
  Setting, 
  Expand, 
  Fold, 
  FolderOpened, 
  Document,
  Plus,
  Minus,
  Select,
  Close
} from '@element-plus/icons-vue'


// Store imports
import { useHistoryStore } from '../stores/history'
import { useUIStore } from '../stores/ui'

// Component imports
import FileTreeNode from '../components/FileTreeNode.vue'
import FileInfoPanel from '../components/FileInfoPanel.vue'
import FileHistoryPanel from '../components/FileHistoryPanel.vue'
import FilePreviewPanel from '../components/FilePreviewPanel.vue'

// Types
import type { FileTreeNode as FileTreeNodeType, FileHistoryRecord } from '../types/basic'

// Store instances
const historyStore = useHistoryStore()
const uiStore = useUIStore()

// Store state - using computed refs
const versions = computed(() => historyStore.versions)
const currentVersion = computed(() => historyStore.currentVersion)
const currentVersionFiles = computed(() => historyStore.currentVersionFiles)
const selectedFiles = computed(() => historyStore.selectedFiles)
const expandedFolders = computed(() => historyStore.expandedFolders)
const isLoading = computed(() => historyStore.isLoading)
const error = computed(() => historyStore.error)
const hasVersions = computed(() => historyStore.hasVersions)
const currentVersionData = computed(() => historyStore.currentVersionData)

const {
  sidebarCollapsed,
  panelSizes,
  toggleSidebar
} = uiStore

// Local state
const showSettings = ref(false)
const showDetailsPanel = ref(true)
const activeDetailsTab = ref('info')
const selectedFileInfo = ref<FileTreeNodeType | null>(null)
const selectedFileHistory = ref<FileHistoryRecord[] | null>(null)
const selectedFilePreview = ref<{ content: string; path: string } | null>(null)

// Settings
const autoRefresh = ref(false)
const showHiddenFiles = ref(false)
const fileSizeFormat = ref<'bytes' | 'human'>('human')

// Methods
async function refreshVersions() {
  try {
    await historyStore.loadVersions()
    if (versions.value.length > 0 && !currentVersion.value) {
      // Auto-select the most recent version
      await selectVersion(versions.value[0].id)
    }
    uiStore.showSuccess('版本列表已刷新')
  } catch (err) {
    uiStore.showError('刷新失败', err instanceof Error ? err.message : '未知错误')
  }
}

async function selectVersion(versionId: string) {
  try {
    await historyStore.selectVersion(versionId)
    // Clear details panel when switching versions
    clearDetailsPanel()
  } catch (err) {
    uiStore.showError('选择版本失败', err instanceof Error ? err.message : '未知错误')
  }
}

function toggleFileSelection(fileId: string) {
  historyStore.toggleFileSelection(fileId)
}

function selectAllFiles() {
  historyStore.selectAllFiles()
}

function clearSelection() {
  historyStore.clearSelection()
  clearDetailsPanel()
}

function toggleFolder(folderPath: string) {
  historyStore.toggleFolder(folderPath)
}

function expandAllFolders() {
  historyStore.expandAllFolders()
}

function collapseAllFolders() {
  historyStore.collapseAllFolders()
}

async function showFileInfo(node: FileTreeNodeType) {
  selectedFileInfo.value = node
  showDetailsPanel.value = true
  activeDetailsTab.value = 'info'
}

async function showFileHistory(node: FileTreeNodeType) {
  try {
    const history = await historyStore.getFileHistory(node.path)
    selectedFileHistory.value = history
    showDetailsPanel.value = true
    activeDetailsTab.value = 'history'
  } catch (err) {
    uiStore.showError('获取文件历史失败', err instanceof Error ? err.message : '未知错误')
  }
}

async function previewFile(node: FileTreeNodeType) {
  if (!currentVersion.value || node.type !== 'file') return
  
  try {
    const content = await historyStore.getFileContent(currentVersion.value, node.id)
    selectedFilePreview.value = {
      content,
      path: node.path
    }
    showDetailsPanel.value = true
    activeDetailsTab.value = 'preview'
  } catch (err) {
    uiStore.showError('预览文件失败', err instanceof Error ? err.message : '未知错误')
  }
}

function clearDetailsPanel() {
  selectedFileInfo.value = null
  selectedFileHistory.value = null
  selectedFilePreview.value = null
}

function saveSettings() {
  // Save settings to localStorage or store
  localStorage.setItem('history-browser-settings', JSON.stringify({
    autoRefresh: autoRefresh.value,
    showHiddenFiles: showHiddenFiles.value,
    fileSizeFormat: fileSizeFormat.value
  }))
  showSettings.value = false
  uiStore.showSuccess('设置已保存')
}

function loadSettings() {
  try {
    const saved = localStorage.getItem('history-browser-settings')
    if (saved) {
      const settings = JSON.parse(saved)
      autoRefresh.value = settings.autoRefresh ?? false
      showHiddenFiles.value = settings.showHiddenFiles ?? false
      fileSizeFormat.value = settings.fileSizeFormat ?? 'human'
    }
  } catch (err) {
    console.warn('Failed to load settings:', err)
  }
}

// Utility functions
function formatVersionId(id: string): string {
  return id.startsWith('-') ? id.substring(1, 9) : id.substring(0, 8)
}

function formatDate(timestamp: number): string {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Watchers
watch(error, (newError) => {
  if (newError) {
    uiStore.showError('操作失败', (newError as unknown as Error)?.message || String(newError))
    historyStore.clearError()
  }
})

// Auto-refresh functionality
let refreshInterval: number | null = null

watch(autoRefresh, (enabled) => {
  if (enabled) {
    refreshInterval = window.setInterval(refreshVersions, 30000) // 30 seconds
  } else if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
})

// Lifecycle
onMounted(async () => {
  loadSettings()
  await refreshVersions()
})

// Cleanup
onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.history-browser {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.browser-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--el-color-primary-light-9);
  border-bottom: 1px solid var(--el-border-color);
  padding: 0 20px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h2 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.main-container {
  flex: 1;
  height: calc(100vh - 60px);
}

.version-sidebar {
  border-right: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color-page);
  transition: width 0.3s ease;
}

.sidebar-header {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid var(--el-border-color);
  gap: 8px;
}

.sidebar-title {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.version-list {
  height: calc(100% - 49px);
  padding: 8px;
}

.version-items {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.version-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.version-item:hover {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-7);
}

.version-item.active {
  background-color: var(--el-color-primary-light-8);
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.version-info {
  flex: 1;
}

.version-id {
  font-weight: 500;
  font-family: 'Courier New', monospace;
  margin-bottom: 4px;
}

.version-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.entries-icon {
  color: var(--el-color-success);
}

.content-container {
  flex: 1;
}

.file-tree-container {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.tree-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color-page);
}

.tree-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.tree-content {
  flex: 1;
  height: calc(100% - 65px);
  padding: 8px 20px;
}

.details-panel {
  border-left: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color-page);
}

.details-header {
  position: relative;
  height: 100%;
}

.close-details {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
}

.loading-placeholder,
.empty-placeholder {
  padding: 20px;
  text-align: center;
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

/* Responsive design */
@media (max-width: 1200px) {
  .details-panel {
    width: 300px !important;
  }
}

@media (max-width: 768px) {
  .browser-header {
    padding: 0 12px;
  }
  
  .header-left h2 {
    font-size: 16px;
  }
  
  .tree-header {
    padding: 12px 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .tree-actions {
    display: flex;
    justify-content: center;
  }
  
  .details-panel {
    width: 280px !important;
  }
}
</style>